
import { message } from "antd";
import axios,{AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse} from "axios"


class HTTP{
    private readonly timeout:number = 10000;
    private readonly baseurl:string = "http://localhost:8080/BookService/";
    private readonly instence:AxiosInstance

    constructor(){
        this.instence = axios.create({
            baseURL:this.baseurl,
            timeout:this.timeout,
            headers:{
                "Content-Type":"application/json"
            }
        })
        this.instence.interceptors.response.use(
            this.handleResponseSuccess,
            this.handleResponseError
        )
        
    }

    // 响应成功拦截器
    handleResponseSuccess(response:AxiosResponse<any>):any{
        if(response.data.data){
            return response.data.data
        } 
        else {
            return response.data
        }
    }
    // 响应失败拦截器
    handleResponseError(err:AxiosError):any{
        const responseState = err.response?.status
        const responseData:any = err.response?.data
        const errInfo = responseData.info
        message.error(errInfo)
        return responseState
    }





    // 各种请求方式
    public get<T>(url:string,config?:AxiosRequestConfig):Promise<T>{
        const result = this.instence.get<T>(url,config) as Promise<T>
        return result
    }

    public post<T>(url:string,body:String,config?:AxiosRequestConfig):Promise<T>{
        return this.instence.post<T>(url,body,config) as Promise<T>
    }

}

export const http = new HTTP();